<template>
  <div class="disaster-view-container">
    <div class="main-content">
      <!-- 地图容器 -->
      <div id="viewDiv" class="map-view"></div>

      <!-- 右侧功能面板 -->
      <div class="control-panel">
        <el-card class="control-card">
          <template #header>
            <div class="card-header">
              <span>灾情信息查看</span>
              <div class="water-drop"></div>
            </div>
          </template>

          <!-- 表格工具栏 -->
          <div class="table-toolbar">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索灾情名称"
              class="search-input"
              clearable
              @clear="loadDisasters"
              @keyup.enter="searchDisasters"
            >
              <template #append>
                <el-button @click="searchDisasters">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
            <el-button type="primary" @click="loadDisasters">
              <el-icon><Refresh /></el-icon> 刷新数据
            </el-button>
          </div>

          <!-- 灾情信息表格 -->
          <el-table
            :data="disasterList"
            style="width: 100%"
            border
            stripe
            height="calc(100vh - 280px)"
            v-loading="loading"
            @row-click="handleRowClick"
          >
            <el-table-column prop="attributes.Name" label="名称" min-width="120" />
            <el-table-column prop="attributes.DisasterType" label="类型" width="100" />
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row)" size="small">
                  {{ getStatusText(scope.row) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-button size="small" type="primary" @click.stop="viewDisasterDetail(scope.row)">
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页控件 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 灾情详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="灾情详细信息"
      width="60%"
      destroy-on-close
      custom-class="disaster-dialog"
    >
      <div v-if="selectedDisaster" class="disaster-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="名称">{{
            selectedDisaster.attributes.Name
          }}</el-descriptions-item>
          <el-descriptions-item label="灾难类型">
            {{ selectedDisaster.attributes.DisasterType }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedDisaster)">
              {{ getStatusText(selectedDisaster) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ selectedDisaster.attributes.Description }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="photo-container" v-if="selectedDisaster.attributes.Photo">
          <h3>现场照片</h3>
          <img :src="selectedDisaster.attributes.Photo" class="disaster-photo" />
        </div>

        <!-- 受灾情况信息 -->
        <div class="disaster-impact-container" v-if="hasDisasterDisasterMessageJson(selectedDisaster)">
          <h3>受灾情况</h3>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="受灾人数">
              {{ getDisasterDisasterMessageJson(selectedDisaster, 'affectedPeople') }} 人
            </el-descriptions-item>
            <el-descriptions-item label="受伤人数">
              {{ getDisasterDisasterMessageJson(selectedDisaster, 'injuredPeople') }} 人
            </el-descriptions-item>
            <el-descriptions-item label="死亡人数">
              {{ getDisasterDisasterMessageJson(selectedDisaster, 'deathCount') }} 人
            </el-descriptions-item>
            <el-descriptions-item label="无家可归人数">
              {{ getDisasterDisasterMessageJson(selectedDisaster, 'homelessPeople') }} 人
            </el-descriptions-item>
            <el-descriptions-item label="经济损失">
              {{ getDisasterDisasterMessageJson(selectedDisaster, 'economicLoss') }} 万元
            </el-descriptions-item>
            <el-descriptions-item label="受灾面积">
              {{ getDisasterDisasterMessageJson(selectedDisaster, 'affectedArea') }} km²
            </el-descriptions-item>
            <el-descriptions-item label="救援队伍数量">
              {{ getDisasterDisasterMessageJson(selectedDisaster, 'rescueTeams') }} 个
            </el-descriptions-item>
            <el-descriptions-item label="救援人员数量">
              {{ getDisasterDisasterMessageJson(selectedDisaster, 'rescuePersonnel') }} 人
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import gcoord from 'gcoord'

// 状态变量
const loading = ref(false)
const disasterList = ref<any[]>([])
const selectedDisaster = ref<any>(null)
const showDetailDialog = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)

// 地图和图层引用
let view: MapView | null = null
let disasterLayer: FeatureLayer | null = null

onMounted(() => {
  initMap()
  loadDisasters()
})

onUnmounted(() => {
  if (view) {
    view = null
  }
})

// 初始化地图
const initMap = () => {
  try {
    // 创建地图实例
    const map = new Map({
      basemap: {
        baseLayers: [gaodeLayer],
      },
    })

    // 创建地图视图
    view = new MapView({
      container: 'viewDiv',
      map: map,
      center: [117.0203, 36.6683], // 山东省济南市的经纬度
      zoom: 10,
    })

    // 创建灾难点要素图层
    disasterLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/chXsWZj8U6NqFZb6/arcgis/rest/services/DisasterDetectionAndRescueSystem/FeatureServer/0',
      outFields: ['*'], // 获取所有字段
      renderer: {
        type: 'simple',
        symbol: {
          type: 'simple-marker',
          color: [255, 0, 0],
          outline: {
            color: [255, 255, 255],
            width: 2,
          },
          size: 12,
        },
      },
      popupTemplate: {
        title: '{Name}',
        content: [
          {
            type: 'fields',
            fieldInfos: [
              {
                fieldName: 'Name',
                label: '名称',
              },
              {
                fieldName: 'DisasterType',
                label: '灾难类型',
              },
              {
                fieldName: 'Description',
                label: '描述',
              },
            ],
          },
        ],
      },
    })

    // 添加图层到地图
    map.add(disasterLayer)
  } catch (error) {
    console.error('初始化地图失败:', error)
    ElMessage.error('初始化地图失败')
  }
}

// 加载灾情数据
const loadDisasters = async () => {
  if (!disasterLayer) return

  loading.value = true
  try {
    // 构建查询参数
    const query = disasterLayer.createQuery()
    query.outFields = ['*']
    query.returnGeometry = true
    query.where = '1=1' // 查询所有记录
    query.start = (currentPage.value - 1) * pageSize.value
    query.num = pageSize.value

    // 如果有搜索关键词，添加到查询条件
    if (searchKeyword.value) {
      query.where = `Name LIKE '%${searchKeyword.value}%'`
    }

    // 执行查询
    const results = await disasterLayer.queryFeatures(query)

    // 获取总记录数
    const countQuery = disasterLayer.createQuery()
    countQuery.where = query.where
    countQuery.returnGeometry = false
    countQuery.outFields = []
    const countResults = await disasterLayer.queryFeatureCount(countQuery)
    totalCount.value = countResults

    // 更新列表数据
    disasterList.value = results.features.map((feature) => {
      // 在存储前对结果数据进行序列化处理，移除不可序列化的属性
      const safeFeature = JSON.parse(
        JSON.stringify(feature, (key, value) => {
          // 过滤掉ArcGIS特殊属性或不可序列化的对象
          if (key === '__accessor__' || typeof value === 'function' || key.startsWith('_')) {
            return undefined
          }
          return value
        }),
      )
      return safeFeature
    })
  } catch (error) {
    console.error('加载灾情数据失败:', error)
    ElMessage.error('加载灾情数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索灾情
const searchDisasters = () => {
  currentPage.value = 1 // 重置到第一页
  loadDisasters()
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadDisasters()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadDisasters()
}

// 处理行点击事件
const handleRowClick = (row: any) => {
  viewDisasterDetail(row)
}

// 查看灾情详情
const viewDisasterDetail = (disaster: any) => {
  selectedDisaster.value = disaster
  showDetailDialog.value = true

  // 在地图上高亮显示选中的灾情点
  highlightDisasterOnMap(disaster)
}

// 在地图上高亮显示灾情点
const highlightDisasterOnMap = (disaster: any) => {
  if (!view) return

  // 将Web Mercator坐标转换为WGS84坐标
  const disasterPoint = gcoord.transform(
    [disaster.geometry.x, disaster.geometry.y],
    gcoord.EPSG3857,
    gcoord.WGS84,
  )
  // 将视图中心移动到选中点
  view.goTo(
    {
      center: [disasterPoint[0], disasterPoint[1]],
      zoom: 15,
    },
    { duration: 1000 },
  )
}

// 获取灾情状态类型（用于标签颜色）
const getStatusType = (disaster: any) => {
  if (!disaster || !disaster.attributes) return ''

  // 根据确认状态返回不同的类型
  if (disaster.attributes.messageData != '') {
    return 'success' // 已确认
  } else {
    return 'warning' // 未确认
  }
}

// 获取灾情状态文本
const getStatusText = (disaster: any) => {
  if (!disaster || !disaster.attributes) return ''

  // 根据messageData状态返回不同的文本
  if (disaster.attributes.messageData != '') {
    return '已确认'
  } else {
    return '待确认'
  }
}

// 检查是否有受灾情况数据
const hasDisasterDisasterMessageJson = (disaster: any) => {
  console.log(disaster)
  console.log(disaster.attributes.DisasterMessageJson)
  if (!disaster || !disaster.attributes || !disaster.attributes.DisasterMessageJson) return false

  try {
    const DisasterMessageJson = JSON.parse(disaster.attributes.DisasterMessageJson)
    return !!DisasterMessageJson && typeof DisasterMessageJson === 'object'
  } catch {
    return false
  }
}

// 获取受灾情况数据
const getDisasterDisasterMessageJson = (disaster: any, field: string) => {
  if (!hasDisasterDisasterMessageJson(disaster)) return 0

  try {
    const DisasterMessageJson = JSON.parse(disaster.attributes.DisasterMessageJson)
    return DisasterMessageJson.disasterImpact[field] || 0
  } catch {
    return 0
  }
}
</script>

<style scoped>
.disaster-view-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.main-content {
  display: flex;
  height: 100%;
  width: 100%;
  position: relative;
}

.map-view {
  height: 100%;
  width: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 450px;
  z-index: 10;
  max-height: calc(100% - 40px);
  display: flex;
  flex-direction: column;
}

.control-card {
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: bold;
  font-size: 16px;
}

.water-drop {
  width: 20px;
  height: 20px;
  background-color: #409eff;
  border-radius: 50% 50% 50% 0;
  transform: rotate(-45deg);
  position: relative;
}

.table-toolbar {
  display: flex;
  margin-bottom: 15px;
  gap: 10px;
}

.search-input {
  flex: 1;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.disaster-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.photo-container {
  margin-top: 10px;
}

.disaster-photo {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
  border: 1px solid #eee;
}

.disaster-impact-container {
  margin-top: 10px;
}

.disaster-dialog :deep(.el-dialog__body) {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}
</style>
